package com.untrance.shop.core.dao.bean;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.google.appengine.api.datastore.Key;
import com.untrance.shop.common.utils.JpaUtils;
import com.untrance.shop.core.dao.CategoryDao;
import com.untrance.shop.model.Category;

/**
 * @author eugene zadyra
 */
@Repository("categoryDao")
@Transactional(readOnly=true)
public class CategoryDaoBean extends MainDaoBean<Category> implements CategoryDao {
	
	public CategoryDaoBean() {
		super(Category.class);
	}

	@Override
	public List<Category> findChildrenByParentCategoryKey(Key key) {
		Query query = em.createQuery("SELECT c FROM Category c WHERE c.parentCategoryKey=:key");
		query.setParameter("key", key);
		return JpaUtils.getCheckedResultList(query);
	}
	
	@Override
	public List<Category> findFirstLevelCategory() {
		return findChildrenByParentCategoryKey(null);
	}
	
	@Override
	public Key findParentKeyByChildCategoryKey(Key key) {
		Query query = em.createQuery("SELECT c.parentCategoryKey FROM Category c WHERE c.id=:key");
		query.setParameter("key", key);
		return JpaUtils.getSingleResult(query);
	}

	@Override
	public List<Key> findChildrenKeysByParentCategoryKey(Key key) {
		Query query = em.createQuery("SELECT c.id FROM Category c WHERE c.parentCategoryKey=:key");
		query.setParameter("key", key);
		return JpaUtils.getCheckedResultList(query);
	}
}
